﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using SMSAssistant.Model;
using Coding4Fun.Phone.Controls;
using SMSAssistant.Resources;
using Microsoft.Phone.Shell;

namespace SMSAssistant
{
    public partial class MainPage : PhoneApplicationPage
    {
        SmsComposeTask smsTask;
        PhoneCallTask phoneCallTask;
        MarketplaceReviewTask reviewTask;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            App.ViewModel.LoadData();
            //if (!App.ViewModel.IsDataLoaded)
            //{
                
            //}
            BuildApplicationBar();
        }

        private void MenuItem_forward_Click(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            if (element != null)
            {
                var vm = element.DataContext as ItemViewModel;
                if (vm != null)
                {
                    //phoneNumberTask = new PhoneNumberChooserTask();

                    //phoneNumberTask.Completed += (s, ee) =>
                    //{
                    //    if (ee.Error != null)
                    //    {

                    //    }
                    //    else
                    //    {

                    //    }
                    //};
                    //phoneNumberTask.Show();

                    var message = vm.Message;
                    smsTask = new SmsComposeTask
                    {
                        Body = message.Content
                    };
                    smsTask.Show();
                }
            }
        }

        private void MenuItem_delete_Click(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            if (element != null)
            {
                var vm = element.DataContext as ItemViewModel;
                if (vm != null)
                {
                    App.ViewModel.DeleteMessage(vm);

                    var toast = new ToastPrompt
                    {
                        Message = string.Format(Resource.DeleteMessageSucceed),
                        MillisecondsUntilHidden = 1500
                    };
                    toast.Show();
                }
            }
        }

        private void MenuItem_edit_Click(object sender, RoutedEventArgs e)
        {
             var element = sender as FrameworkElement;
             if (element != null)
             {
                 var vm = element.DataContext as ItemViewModel;
                 if (vm != null)
                 {
                     NavigationService.Navigate(new Uri(string.Format("/NewMessageView.xaml?id={0}",vm.Message.Id.ToString()), UriKind.Relative));
                 }
             }
        }

        private void MenuItem_call_Click(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            if (element != null)
            {
                var vm = element.DataContext as ItemViewModel;
                if (vm != null)
                {
                    var message = vm.Message;

                    if (message.Contact != null)
                    {
                        phoneCallTask = new PhoneCallTask
                        {
                            DisplayName = message.Contact.DisplayName,
                            PhoneNumber = message.Contact.PhoneNumber
                        };
                        phoneCallTask.Show();
                    }
                }
            }
        }

        private void MenuItem_copy_Click(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            if (element != null)
            {
                var vm = element.DataContext as ItemViewModel;
                if (vm != null)
                {
                    var message = vm.Message;

                    Clipboard.SetText(message.Content);

                    var toast = new ToastPrompt
                    {
                        Message = string.Format(Resource.CopyMessageSucceed),
                        MillisecondsUntilHidden = 1500
                    };
                    toast.Show();
                }
            }
        }
        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            searchBox.Text = string.Empty;
        }

        private void ButtonSearch_Click(object sender, RoutedEventArgs e)
        {
            //if (string.IsNullOrEmpty(searchBox.Text))
            //{ 
            //}
            //else
            App.ViewModel.Search(searchBox.Text);
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/NewMessageView.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItem2_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/BackUpView.xaml", UriKind.Relative));
        }

        private void ApplicationBarMenuItem3_Click(object sender, EventArgs e)
        {
            reviewTask = new MarketplaceReviewTask();
            reviewTask.Show();
            //this.NavigationService.Navigate(new Uri("/BackUpView.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //base.OnNavigatedTo(e);
            var count = NavigationService.BackStack.Count();
            for (int i = 0; i <
                count; i++)
            {
                if (NavigationService.CanGoBack)
                    NavigationService.RemoveBackEntry();
            }

            App.ViewModel.LoadData();

            if (menu != null && menu.IsOpen)
                menu.IsOpen = false;
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("NewMessageView.xaml"));
            if (tile != null)
            {
                var toast = new ToastPrompt
                {
                    Message = string.Format(Resource.NewMessageAlreadyPined),
                };
                toast.Show();
            }
            else
            {
                StandardTileData tileData = new StandardTileData
                {
                    Title = Resource.NewMessage,
                    Count = 0,
                    BackgroundImage = new Uri("/Images/create_new.png", UriKind.Relative),
                };

                ShellTile.Create(new Uri("/NewMessageView.xaml", UriKind.Relative), tileData);
            }
        }

        private void BuildApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar() { Opacity = .5 };

            // Create a new button and set the text value to the localized string from AppResources.
            ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar.add.rest.png", UriKind.Relative));
            appBarButton.Click += ApplicationBarIconButton_Click;
            appBarButton.Text = Resource.NewMessage;
            ApplicationBar.Buttons.Add(appBarButton);

            // Create a new menu item with the localized string from AppResources.
            ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(Resource.PinToStart);
            appBarMenuItem.Click += ApplicationBarMenuItem_Click;
            ApplicationBar.MenuItems.Add(appBarMenuItem);

            // Create a new menu item with the localized string from AppResources.
            ApplicationBarMenuItem appBarMenuItem2 = new ApplicationBarMenuItem(Resource.BackupMenuItemLabel);
            appBarMenuItem2.Click += ApplicationBarMenuItem2_Click;
            ApplicationBar.MenuItems.Add(appBarMenuItem2);

            // Create a new menu item with the localized string from AppResources.
            ApplicationBarMenuItem appBarMenuItem3 = new ApplicationBarMenuItem(Resource.MenuRateApp);
            appBarMenuItem3.Click += ApplicationBarMenuItem3_Click;
            ApplicationBar.MenuItems.Add(appBarMenuItem3);

            //  <toolkit:MenuItem Click="MenuItem_copy_Click" Header="复制消息"/>
            //<toolkit:MenuItem Click="MenuItem_forward_Click" Header="转发消息"/>
            //<toolkit:MenuItem Click="MenuItem_delete_Click" Header="删除消息"/>
            //<toolkit:MenuItem Click="MenuItem_call_Click" Header="呼叫联系人"/>
            //cMenu.Items.Add
            //MenuItem m1 = new MenuItem { Header = Resource.MenuCopyHeader };
            //m1.Click += MenuItem_copy_Click;
            //cMenu.Items.Add(m1);
            //MenuItem m2 = new MenuItem { Header = Resource.MenuForwardHeader };
            //m2.Click += MenuItem_forward_Click;
            //cMenu.Items.Add(m2);
            //MenuItem m3 = new MenuItem { Header = Resource.MenuDeleteHeader };
            //m3.Click += MenuItem_delete_Click;
            //cMenu.Items.Add(m3);
            //MenuItem m4 = new MenuItem { Header = Resource.MenuCallHeader };
            //m4.Click += MenuItem_call_Click;
            //cMenu.Items.Add(m4);
        }
        ContextMenu menu;
        private void cMenu_Opened(object sender, RoutedEventArgs e)
        {
            menu = sender as ContextMenu;
            if (menu != null && menu.Items.Count==0)
            {
                MenuItem m1 = new MenuItem { Header = Resource.MenuCopyHeader };
                m1.Click += MenuItem_copy_Click;
                menu.Items.Add(m1);
                MenuItem m2 = new MenuItem { Header = Resource.MenuForwardHeader };
                m2.Click += MenuItem_forward_Click;
                menu.Items.Add(m2);
                MenuItem m3 = new MenuItem { Header = Resource.MenuDeleteHeader };
                m3.Click += MenuItem_delete_Click;
                menu.Items.Add(m3);
                MenuItem m4 = new MenuItem { Header = Resource.MenuCallHeader };
                m4.Click += MenuItem_call_Click;
                menu.Items.Add(m4);
                //MenuItem m5 = new MenuItem { Header = Resource.MenuEditHeader };
                //m5.Click += MenuItem_edit_Click;
                //menu.Items.Add(m5);
            }
        }

        private void messageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var vm = e.AddedItems[0] as ItemViewModel;
                if (vm != null)
                {
                    NavigationService.Navigate(new Uri(string.Format("/NewMessageView.xaml?id={0}", vm.Message.Id.ToString()), UriKind.Relative));
                }
            }
        }

        
    }
}